package com.itheima.prize.api.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.prize.commons.config.RedisKeys;
import com.itheima.prize.commons.db.entity.CardUser;
import com.itheima.prize.commons.db.mapper.CardUserMapper;
import com.itheima.prize.commons.db.service.CardUserService;
import com.itheima.prize.commons.utils.ApiResult;
import com.itheima.prize.commons.utils.PasswordUtil;
import com.itheima.prize.commons.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping(value = "/api")
@Api(tags = {"登录模块"})
public class LoginController {
    @Autowired
    private CardUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    private static final int MAX_ERROR_COUNT = 5;
    private static final long FREEZE_TIME = 5 * 60;


    @PostMapping("/login")
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    public ApiResult login(HttpServletRequest request, @RequestParam String account, @RequestParam String password) {
        //TODO
        String redisKey = "userError:" + account;
        Object value = redisUtil.get(redisKey);
        //检查是否处于冻结状态
        if (redisUtil.hasKey(redisKey) && value instanceof Integer && (Integer) value >= MAX_ERROR_COUNT) {
            return new ApiResult<>(0, "由于您试错5次，请在" + (redisUtil.getExpire(redisKey) / 60) + "分钟后再试", null);
        }
        String encodePassword = PasswordUtil.encodePassword(password);
        QueryWrapper<CardUser> wrapper = new QueryWrapper<>();
        wrapper.eq("uname", account).eq("passwd", encodePassword);
        List<CardUser> cardUserList = userService.list(wrapper);

        if (cardUserList.isEmpty()) {
            //登录失败，增加错误次数
            long incr = redisUtil.incr(redisKey, 1);
            // 检查是否已设置过期时间，若未设置则设置
            redisUtil.expire(redisKey, FREEZE_TIME);
            if (incr < MAX_ERROR_COUNT) {
                return new ApiResult<>(0, "您已经重试" + incr + "次,还有" + (MAX_ERROR_COUNT - incr) + "次重试机会", null);
            }
            if (incr == MAX_ERROR_COUNT) {
                return new ApiResult<>(0, "由于您试错5次，请稍后再试", null);
            }
        }
        //如果登录成功，清除错误次数记录
        redisUtil.del(redisKey);
        CardUser user = cardUserList.get(0);
        user.setIdcard(null);
        user.setPasswd(null);
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        return new ApiResult<>(1, "登录成功", user);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出")
    public ApiResult logout(HttpServletRequest request) {
        //TODO
        HttpSession session = request.getSession();
        if (session != null) {
            //清除指定属性
            session.removeAttribute("user");
            //使对话失效
            session.invalidate();
        }
        return new ApiResult<>(0, "退出成功", null);
    }

}